package com.ec.pf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ec.api.client.UserClient;
import com.ec.common.domain.Result;
import com.ec.common.exception.BadRequestException;
import com.ec.pf.mapper.ElderlyProfileMapper;
import com.ec.pf.pojo.ElderlyProfile;
import com.ec.pf.service.ElderlyProfileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ElderlyProfileServiceImpl extends ServiceImpl<ElderlyProfileMapper, ElderlyProfile> implements ElderlyProfileService {

    private final ElderlyProfileMapper elderlyProfileMapper;
    private final UserClient userClient;

    // 新增老人档案
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ElderlyProfile addElderlyProfile(ElderlyProfile elderlyProfile) {
        // 验证 user_id 是否存在
        Result<Boolean> existsResult = userClient.checkUserExists(elderlyProfile.getUserId());
        if (!existsResult.getData()) {
            throw new BadRequestException("用户ID不存在");
        }

        boolean saved = this.save(elderlyProfile);
        if (saved) {
            return elderlyProfile;
        } else {
            throw new RuntimeException("新增老人档案失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteElderlyProfileById(Long id) {
        // 检查老人档案是否存在
        ElderlyProfile elderlyProfile = this.getById(id);
        if (elderlyProfile != null) {
            // 使用 MyBatis-Plus 提供的 removeById 方法来删除
            boolean removed = this.removeById(id); // 直接从数据库中删除该记录
            if (removed) {
                return true;
            } else {
                throw new RuntimeException("删除老人档案失败");
            }
        } else {
            throw new RuntimeException("老人档案未找到");
        }
    }


    // 修改老人档案
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ElderlyProfile updateElderlyProfile(ElderlyProfile elderlyProfile) {
        boolean updated = this.updateById(elderlyProfile);
        if (updated) {
            return elderlyProfile;
        } else {
            throw new RuntimeException("更新老人档案失败");
        }
    }

    // 根据 ID 查询老人档案
    @Override
    public ElderlyProfile getElderlyProfileById(Long id) {
        ElderlyProfile elderlyProfile = this.getById(id);
        if (elderlyProfile == null) {
            throw new RuntimeException("老人档案未找到");
        }
        return elderlyProfile;
    }

    // 分页查询老人档案
    @Override
    public Page<ElderlyProfile> listElderlyProfiles(Integer page, Integer size) {
        Page<ElderlyProfile> elderlyProfilePage = new Page<>(page, size);
        QueryWrapper<ElderlyProfile> queryWrapper = new QueryWrapper<>();
        // 可以根据业务需求添加查询条件
        this.page(elderlyProfilePage, queryWrapper);
        return elderlyProfilePage;
    }

    // 模糊查询老人档案
    @Override
    public Page<ElderlyProfile> searchElderlyProfiles(String fullName, String idCardNumber, String gender, int page, int size) {
        Page<ElderlyProfile> elderlyProfilePage = new Page<>(page, size);
        QueryWrapper<ElderlyProfile> queryWrapper = new QueryWrapper<>();

        if (fullName != null && !fullName.isEmpty()) {
            queryWrapper.like("full_name", fullName); // 模糊查询姓名
        }
        if (idCardNumber != null && !idCardNumber.isEmpty()) {
            queryWrapper.like("id_card_number", idCardNumber); // 模糊查询身份证号
        }
        if (gender != null && !gender.isEmpty()) {
            queryWrapper.like("gender", gender); // 模糊查询性别
        }

        return this.page(elderlyProfilePage, queryWrapper);
    }


    // 批量删除老人档案
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteElderlyProfiles(List<Long> ids) {
        boolean removed = this.removeByIds(ids);
        if (removed) {
            return true;
        } else {
            throw new RuntimeException("批量删除老人档案失败");
        }
    }

    // 更新老人状态（例如：在住、退住、临时外出）
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateElderlyCheckInStatus(Long id, String status) {
        ElderlyProfile elderlyProfile = this.getById(id);
        if (elderlyProfile != null) {
            elderlyProfile.setCheckInStatus(status);
            boolean updated = this.updateById(elderlyProfile);
            if (updated) {
                return true;
            } else {
                throw new RuntimeException("更新老人状态失败");
            }
        } else {
            throw new RuntimeException("老人档案未找到");
        }
    }
}
